package com.building18.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.building18.handler.MyAssert;
import com.building18.handler.exception.MyException;
import com.building18.pojo.*;
import com.building18.pojo.enums.BuildingCode;
import com.building18.pojo.enums.Code;
import com.building18.service.PermissionService;
import com.building18.utils.MinioUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/permission")
@Tag(name = "权限管理", description = "权限管理")
public class PermissionController {
    @Autowired
    private PermissionService permissionService;

    @Autowired
    private MinioUtils minioUtils;

    @GetMapping("/{pageNum}/{pageSize}")
    @Operation(summary = "查询所有权限信息（分页）")
    public Result<?> getAllPermission(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Permission> permission = permissionService.selectPermission();
        PageInfo<Permission> permissionPageInfo = new PageInfo<>(permission);
        MyPageData myPageData = new MyPageData(permissionPageInfo.getTotal(), permissionPageInfo.getList());
        return Result.ok(myPageData, Code.SELECT_SUCCESS.getMessage());
    }


    /**
     *
     * @param id 当前选中的角色
     * 封装 查询所有的权限 id + 名称
     * 封装 查询所有的 当前所选角色的 权限id + 名称
     */

    @GetMapping("/{id}")
    @Operation(summary = "查询所有权限信息(分级树)")
    public Result<?> getAllPerms(@PathVariable Integer id) {
        HashMap<String, List> allPerms = permissionService.getAllPerms(id);
        return Result.ok(allPerms, Code.SELECT_SUCCESS.getMessage());
    }



/**
 * @param id 要更改的角色ID
 * @param ids 要更改的权限ID列表
 */
    @PostMapping("/{id}")
    @Operation(summary = "保存更新的权限信息")
    public Result<?> saveNewPerms(@PathVariable Integer id, @RequestBody List<Integer> ids) {
    // 调用permissionService的saveNewPerms方法保存权限信息，并获取更新的数量
        Integer i=permissionService.saveNewPerms(id, ids);
    // 返回操作成功的结果，包含更新的数量和预设的成功消息
        return Result.ok(i, Code.UPDATE_SUCCESS.getMessage());
    }


    @PutMapping("updatePermission")
    @Operation(summary = "更新权限信息")
    public Result<?> updatePermission(@RequestBody Permission permission) {
        Integer i=permissionService.updatePermission(permission);
         return Result.ok(i, Code.UPDATE_SUCCESS.getMessage());
    }


    @DeleteMapping("deletePermission/{id}")
    @Operation(summary = "删除权限信息")
    public Result<?> deletePermission(@PathVariable("id") Integer id) {
         Integer i=permissionService.deletePermission(id);
         return Result.ok(i, Code.DELETE_SUCCESS.getMessage());
    }

    @PostMapping("/upload")
    public Result<?> uploadPermFile(@RequestParam MultipartFile file) throws IOException {
        //读取收到的这个excel文件
        // 将里面数据解析出来
        EasyExcel.read(file.getInputStream(), Permission.class, new PageReadListener<Permission>(data -> {
            permissionService.addPermsByFile(data);
        })).sheet().doRead();
        // 做批量新增
        return Result.ok(null, BuildingCode.SAVE_PERMS_SUCCESS.getMessage());
    }

    @GetMapping("/downloadPermModel/{permModel}")
    @Operation(summary = "下载权限模板")
    public ResponseEntity<byte[]> downloadPermModel(@PathVariable String permModel) {
        try {
            ResponseEntity<byte[]> fileResponse = minioUtils.download(permModel);

            // 添加自定义响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add("X-Download-Filename", permModel);
            headers.add("X-Download-Message", BuildingCode.DOWNLOAD_SUCCESS.getMessage());
            headers.add("Access-Control-Expose-Headers", "X-Download-Filename, X-Download-Message");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileResponse.getBody());

        } catch (Exception e) {
            throw new MyException(Result.fail(BuildingCode.DOWNLOAD_FAIL.getMessage() + e.getMessage()));
        }
    }


    @GetMapping("/beforeDeleteRole/{id}")
    @Operation(summary = "删除角色前查询")
    public Result<?> beforeDeleteRole(@PathVariable("id") Integer id) {
        permissionService.beforeDeleteRole(id);
        return Result.ok(Code.CAN_DELETE.getMessage());
    }

    @GetMapping("/selectAllMenuPerms")
    @Operation(summary = "查询当前角色权限")
    public Result<?> selectRole(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Permission> permissions = permissionService.selectAllMenuPerms(user.getId());
        return Result.ok(permissions, Code.SELECT_SUCCESS.getMessage());
    }

}
